const express = require('express')
const database = require('../../database')
const jwt = require('jsonwebtoken')//签发token
const secretKey = require('../../secret/secretKey.js')

const router = express.Router()

router.post('/login', (request, response) => {
    const sql = 'select * from user where username = ? && password = ?'
    const info = request.body
    console.log(`收到来自${info.username}的登录请求...`)
    database.query(sql, [info.username, info.password], (error, result) => {
        if(error) {
           response.status(417).end()//执行失败状态码417
        } else {
            if(result.length) {
                response.send({
                    allowed: true,
                    token: jwt.sign({username: info.username}, secretKey, {expiresIn: '24h'})
                })
            } else {
                response.send({
                    allowed: false
                })
            }
        }
    })
})

module.exports = router